package com.shuo.dsa.test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by shuoGG on 2018/10/26 0026
 */
public class PrintN_Ali {
    private int counter;
    private char[] ret;
    private AtomicInteger index = new AtomicInteger(0);
    private CountDownLatch latch = null;

    private class Thread1 extends Thread {
        private int tIndex = 0;

        public Thread1(int nTime) {
            int total = nTime * 3;
            latch = new CountDownLatch(total);
            counter = nTime;
            ret = new char[total];
        }

        @Override
        public void run() {
            while (tIndex < counter) {
                synchronized (PrintN_Ali.class) {
                    if (index.intValue() % 3 == 0) {
                        ret[index.intValue()] = 'A';
                        index.incrementAndGet();
                        tIndex++;
                        latch.countDown();
                    }
                }
            }
        }
    }

    private class Thread2 extends Thread {
        private int tIndex = 0;

        @Override
        public void run() {
            while (tIndex < counter) {
                synchronized (PrintN_Ali.class) {
                    if (index.intValue() % 3 == 1) {
                        ret[index.intValue()] = 'l';
                        index.incrementAndGet();
                        tIndex++;
                        latch.countDown();
                    }
                }
            }
        }
    }

    private class Thread3 extends Thread {
        private int tIndex = 0;

        @Override
        public void run() {
            while (tIndex < counter) {
                synchronized (PrintN_Ali.class) {
                    if (index.intValue() % 3 == 2) {
                        ret[index.intValue()] = 'i';
                        latch.countDown();
                        index.incrementAndGet();
                        tIndex++;
                    }
                }
            }
        }
    }

    public String getAliStr(int nTime) throws InterruptedException {
        new Thread1(nTime).start();
        new Thread2().start();
        new Thread3().start();
        latch.await();
        return new String(ret);
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println(new PrintN_Ali().getAliStr(1000));
    }
}